#version 120 

// particle data textures
uniform sampler2D positions;
uniform sampler2D velocities;
uniform sampler2D infos;
uniform float emitProb;

uniform vec3 randomSeed;

float rand (vec2 n){
  return fract(sin(dot(n.xy, randomSeed.xy))* randomSeed.z);
}

void main(){

	vec3 newPos = texture2D (positions, gl_TexCoord[0].xy).xyz;
	vec3 newVel = texture2D (velocities, gl_TexCoord[0].xy).xyz;
	vec3 newInf = texture2D (infos, gl_TexCoord[0].xy).xyz;
	
	// emit if slot empty and with given probability
	if (newInf.x==0 && rand(gl_TexCoord[0].xy) < emitProb) {
	
		// calculate point on rect
		int W = 1050;
		int H = 450;
		
		float x = rand(gl_TexCoord[0].xy+vec2(1000,0))*W-W/2;
		float y = 200;
		float z = rand(gl_TexCoord[0].xy+vec2(2000,0))*H-H/2;
		
		// position on sphere
		newPos = vec3(x,y,z);
		
		// radial initial speed impulse
		newVel = vec3(0);
		
		// set lifetime
		float lifeTime = rand(gl_TexCoord[0].xy+vec2(300,0))*3+6;
		newInf = vec3(lifeTime,0,0);
	}
	
	gl_FragData[0] = vec4(newPos,1);
	gl_FragData[1] = vec4(newVel,1);	// no initial velocity
	gl_FragData[2] = vec4(newInf,1);    // lifetime 1 second
}